﻿using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.Common.Service;
using ContractManager.BLL.Business;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Forms
{
    public partial class FrmDicts : XtraFormBase
    {
        #region "Define Variable"

        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        private int _invId;

        private bool _allowAdd;
        private bool _allowDelete;
        private bool _allowEdit;
        private bool _allowAccess;
        private bool _allowPrint;

        private bool _isPersonVoucher;
        private bool _isInvoice;

        private int _formNo;
        private string _reportName;
        private string _listLockDate;
        private string _currentDate;

        
        #endregion

        #region "Form Construction"
        public FrmDicts()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"
        private static GridCheckMarksSelection InitSelection(GridView gv)
        {
            var gridCheckMarksSelection = new GridCheckMarksSelection(gv);

            for (var i = 0; i < gv.Columns.Count; i++)
            {
                if (gv.Columns[i].Visible)
                {
                    gv.Columns[i].VisibleIndex += 1;    
                }
            }
            gridCheckMarksSelection.CheckMarkColumn.VisibleIndex =0;
            gridCheckMarksSelection.CheckMarkColumn.Width=60;
            return gridCheckMarksSelection;
        }

        private string GetSelectRow(GridCheckMarksSelection gridCheckMarksSelection)
        {
            string strRet = String.Empty;

            for (var i = 0; i < gridCheckMarksSelection.SelectedCount; i++)
            {
                var rowView = (DataRowView)gridCheckMarksSelection.GetSelectedRow(i);
                strRet = String.IsNullOrEmpty(strRet) ? 
                    String.Format("{0}", rowView[FieldNameId]) :
                    String.Format("{0},{1}", strRet, rowView[FieldNameId]);
            }

           return strRet;
        }

        private void CheckPer()
        {
           /* _menu = new Entity.Menu { Id = ClsVariable.EmployeeId, FormNo = _formNo };
            _objMenu.Report = _menu;
            using (DataTable dt = _objMenu.SelectByUserFormNo())
            {
                if (dt == null) return;
                _allowAdd = (bool)dt.Rows[0]["AllowAdd"];
                _allowDelete = (bool)dt.Rows[0]["AllowDelete"];
                _allowEdit = (bool)dt.Rows[0]["AllowEdit"];
                _allowAccess = (bool)dt.Rows[0]["AllowAccess"];
                _allowPrint = (bool)dt.Rows[0]["AllowPrint"]; 
            }*/
        }

        private void LockMenu(bool mnlock)
        {
            bool condition = _isPersonVoucher || (ClsVariable.IsEditVoucher);
            btnNew.Enabled = _allowAdd;
            btnEdit.Enabled = !mnlock && _allowEdit && condition && _listLockDate.Contains(_currentDate)==false;
            btnDelete.Enabled = !mnlock && _allowDelete && condition && _listLockDate.Contains(_currentDate) == false;
            btnView.Enabled = !mnlock && _allowAccess;
            btnPrint.Enabled = _allowPrint;
            
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                grdInvestors.DataSource = null;
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void DoNew()
        {
            var frm = new FrmInvestorDetail()
            {
                InvestorId = 0,
                AsSysBillStyleId = 0,
                AsSysMyCoYearId = 0,
                AsPerPersonId = 0,
                FormNo = _formNo,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                Text = String.Format("Thông tin {0}", this.Text),
                
                MdiParent = this.MdiParent,
                WindowState = FormWindowState.Maximized
            };
           // frm.Closed += frm_Closed;
            frm.Show();
            frm.Focus();
        }

        private void DoEdit()
        {
            var frm = new FrmInvestorDetail()
            {
                InvestorId = _invId,
                AsSysBillStyleId = 0,
                AsSysMyCoYearId = 0,
                AsPerPersonId = 0,
                FormNo = _formNo,
                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
               
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,

                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };
           // frm.Closed += frm_Closed;
            frm.Show();
            frm.Focus();
        }

        private void DoView()
        {
            var frm = new FrmInvestorDetail()
            {
                InvestorId = _invId,
                AsSysBillStyleId = 0,
                AsSysMyCoYearId = 0,
                AsPerPersonId = 0,
                FormNo = _formNo,
                OnlyView = true,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,

                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,

                Text = String.Format("Thông tin {0}", this.Text),
                MdiParent = this.MdiParent,
                
                WindowState = FormWindowState.Maximized
            };

            frm.Show();
            frm.Focus();
        }

        private void DoDelete()
        {
            string strMasterId = GetSelectRow(GcmSelection) != null ? GetSelectRow(GcmSelection) : _invId.ToString();
            if (strMasterId.Length== 0) return;
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xoá bản ghi hiện tại không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                switch (FormType)
                {
                    case 1:
                        ClsCategories.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 2:
                        ClsContractStatus.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 3:
                        ClsCapitals.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 4:
                        ClsExchangeType.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 5:
                        ClsWorkType.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 6:
                        ClsResources.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 7:
                        ClsDocumentTypes.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 8:
                        ClsInsuranceType.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                    case 9:
                        ClsContractType.DeleteByPk(Convert.ToInt32(strMasterId));
                        break;
                }

                ClsInvestors.DeleteByPk(Convert.ToInt32(strMasterId));
                grvInvestors.DeleteRow(grvInvestors.FocusedRowHandle);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private void DoPrint()
        {
            grdInvestors.ShowPrintPreview();
        }
        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var list = new object();
                switch (FormType)
                {
                    case 1:
                        list = ClsCategories.SelectAll();
                        break;
                    case 2:
                        list = ClsContractStatus.SelectAll();
                        break;
                    case 3:
                        list = ClsCapitals.SelectAll();
                        break;
                    case 4:
                        list = ClsExchangeType.SelectAll();
                        break;
                    case 5:
                        list = ClsWorkType.SelectAll();
                        break;
                    case 6:
                        list = ClsResources.SelectAll();
                        break;
                    case 7:
                        list = ClsDocumentTypes.SelectAll();
                        break;
                    case 8:
                        list = ClsInsuranceType.SelectAll();
                        break;
                    case 9:
                        list = ClsContractType.SelectAll();
                        break;
                }
                e.Result = list;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = () =>
            {
                grdInvestors.DataSource = e.Result;

            };
            grdInvestors.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmDictLoad(object sender, EventArgs e)
        {
            if (Tag != null)
            {
                _formNo = Convert.ToInt32(Tag);
                ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                ClsVariable.SetWaitDialogCaption("Kiểm tra dữ liệu phân quyền...");
                CheckPer();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách chủ đầu tư..."));
                GetData();
                ClsVariable.CloseWaitDialog();
                LockMenu(true);
                FieldNameId = FormType == 1
                                  ? "CatId"
                                  : (FormType == 2
                                         ? "ConStaID"
                                         : (FormType == 3
                                                ? "CapId"
                                                : (FormType == 4
                                                       ? "ExcId"
                                                       : (FormType == 5
                                                              ? "WorkId"
                                                              : (FormType == 6
                                                                     ? "ResId"
                                                                     : (FormType == 7
                                                                            ? "DocTypId"
                                                                            : (FormType == 8
                                                                                   ? "InsTypId"
                                                                                   : (FormType == 9
                                                                                          ? "ConTypId"
                                                                                          : "AttDocId"))))))));
                GcmSelection = InitSelection(grvInvestors);
                grvInvestors.FocusedRowHandle = GridControl.AutoFilterRowHandle;
                RefHelper = new RefreshHelper(grvInvestors, FieldNameId);
                if (!String.IsNullOrEmpty(FormReportLayoutTemplate))
                {
                    string filePath = ClsVariable.GetRestoreLayoutFullPath(FormReportLayoutTemplate);
                    grvInvestors.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                }
            }

        }

        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnNew":
                    DoNew();
                    break;
                case "btnEdit":
                    RefHelper.SaveViewInfo();
                    DoEdit();
                    RefHelper.LoadViewInfo();
                    break;
                case "btnView"://Xem thông tin chứng từ
                    DoView();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnRefresh"://Nạp lại dữ liệu
                    GetData();
                    break;
                case "btnPrint"://In phiếu
                    DoPrint();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdInvestors);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Grid Event"
        private void grvInvestors_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
            {
                _invId = 0;
                LockMenu(true);
                return;
            }
            if (grvInvestors.GetRowCellValue(e.FocusedRowHandle, FieldNameId) != DBNull.Value)
            {
                _invId = Convert.ToInt32(grvInvestors.GetRowCellValue(e.FocusedRowHandle, FieldNameId));
                LockMenu(false);
            }
        }
        #endregion

    }
}
